﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

[RequireComponent(typeof(CanvasGroup))]
public class UIGroupFade : MonoBehaviour
{
    [Header("=====  淡入淡出设置 =====")]
    public float fadeIn = 0;
    public float fadeWait = 2.0f;
    public float fadeOut = 0.5f;


    private float _fadeIn = 0;
    private float _fadeWait = 0f;
    private float _fadeOut = 0f;

    private CanvasGroup canvasGroup;

    public bool isFading { get; private set; }

    public bool autoStart = false;

    public UnityEvent onFadeOut;

    private void Awake()
    {
        canvasGroup = GetComponent<CanvasGroup>();
        StartFade(fadeIn, fadeWait, fadeOut, autoStart);
    }


    /// <summary>
    /// 重置fade 状态
    /// </summary>
    /// <param name="fadeIn"></param>
    /// <param name="fadeWait"></param>
    /// <param name="fadeOut"></param>
    public void StartFade(float fadeIn, float fadeWait, float fadeOut, bool autoStart = true)
    {
        this.fadeIn = fadeIn;
        this.fadeWait = fadeWait;
        this.fadeOut = fadeOut;
        _fadeIn = _fadeWait = _fadeOut = 0;

        if (fadeIn != 0)
        {
            canvasGroup.alpha = 0;
        }else{
            canvasGroup.alpha = 1;
        }

        isFading = autoStart;
    }

    /// <summary>
    /// 重新开始fade
    /// </summary>
    public void Restart()
    {
        _fadeWait = _fadeOut = 0;
        isFading = true;
    }

    public void StartFade()
    {
        isFading = true;
    }

    /// <summary>
    /// 直接fadeout 
    /// </summary>
    public void FadeOut()
    {
        _fadeWait = fadeWait;
        _fadeOut = 0;
        isFading = true;
    }

    // Update is called once per frame
    void Update()
    {
        if (isFading == false) return;

        float dt = Time.deltaTime;
        float alpha = 0;
        if (_fadeIn <= fadeIn && fadeIn != 0)
        {
            _fadeIn += dt;
            alpha = Mathf.SmoothStep(0, 1, _fadeIn / fadeIn);
        }
        else if (_fadeWait <= fadeWait && fadeWait != 0)
        {
            _fadeWait += dt;
            alpha = 1;

        }
        else if (_fadeOut <= fadeOut && fadeOut != 0)
        {
            _fadeOut += dt;
            alpha = Mathf.SmoothStep(1, 0, _fadeOut / fadeOut);
        }
        else
        {
            isFading = false;
            onFadeOut?.Invoke();
        }

        canvasGroup.alpha = alpha;

    }
}
